package com.xxxt.utils;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

public class FileDownUtil {
public static ResponseEntity<byte[]> download(HttpServletRequest request,String path) {
	//获取文件
	File file = new File(path);
	String fileName = file.getName();
    // 对文件名编码，防止中文文件乱码
    try {
		fileName = FileUploadUtil.getFilename(request, fileName);
	} catch (Exception e1) {
		e1.printStackTrace();
		return null;
	}
//	fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
    // 设置响应头
    HttpHeaders headers = new HttpHeaders();
    // 通知浏览器以下载的方式打开文件
    headers.setContentDispositionFormData("attachment", fileName);
    // 定义以二进制流的形式下载返回文件数据
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    // 使用SringMVC的ResponseEntity对象封装返回下载数据,Commons FileUpload组件的FileUtils读取文件
   try {
	return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
	                                           headers,HttpStatus.OK);
} catch (IOException e) {
	e.printStackTrace();
	return null;
}
}
	
}
